// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.platform.diagnostic.telemetry.impl.agent

import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.platform.diagnostic.telemetry.rt.context.TelemetryContext.TRACE_CONTEXT_JVM_PROPERTY_NAME
import org.jetbrains.annotations.ApiStatus
import java.io.File
import kotlin.io.path.pathString

@ApiStatus.Internal
object TelemetryAgentProvider {

  @JvmStatic
  fun getJvmArgs(configuration: AgentConfiguration): List<String> {
    val configLocation = FileUtilRt.createTempFile("otlpAgent", ".properties")
    configuration.writeSettings(configLocation)
    return listOf(
      "-javaagent:${configuration.agentLocation.pathString}",
      "-Dotel.javaagent.configuration-file=${FileUtilRt.toSystemDependentName(configLocation.absolutePath)}",
      "-D$TRACE_CONTEXT_JVM_PROPERTY_NAME=${configuration.context.asString()}",
      "-Dotel.service.name=${configuration.serviceName}"
    )
  }

  private fun AgentConfiguration.writeSettings(target: File) {
    target.writer(Charsets.UTF_8)
      .use { writer ->
        val serializedConfig = toJavaAgentSettings()
        serializedConfig.store(writer, "Generated by Intellij IDEA")
      }
  }
}
